import router from '@/router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'


// 通用请求配置
const request = axios.create({
  baseURL: '/api',
  timeout: 60000,
  withCredentials:true
})

// 添加一个请求拦截器
request.interceptors.request.use(
  config => {
    if (!getToken()) {
      router.push('/login')
    }
    // Do something before request is sent
    return config
  },
  error => {
    // Do something with request error
    Promise.reject(error)
  },
)

// 添加一个响应拦截器
request.interceptors.response.use(
  response => {
    return response
    // const { data } = response
    // const { code, msg } = data
    // if (code === 200) {
    //   return response.data
    // } else if (code === 500) {
    //   ElMessage.error(`服务器内部错误，请联系管理员进行处理。`)
    // } else {
    //   ElMessage.error(msg)
    // }
  },
  error => {
    const { message, response } = error
    if (response.status === 400) {
      if(response.data.code===-20004){
        ElMessage.error("存在绑定的用户,对象无法删除")
      }else{
        ElMessage.error(response.data.msg)
      }
      return Promise.reject(response)
    } else if (message === 'Network Error') {
      ElMessage.error('服务器接口连接异常')
    } else if (message.includes('timeout')) {
      ElMessage.error('服务器接口请求超时')
    } else if (message.includes('Request failed with status code')) {
      ElMessage.error('服务器内部接口 ' + message.substr(message.length - 3) + ' 异常')
    } else {
      return Promise.reject(error)
    }
  },
)

export default request
